package cn.madis.ymcc.mq.listener;

import cn.madis.ymcc.domain.CourseOrder;
import cn.madis.ymcc.domain.dto.Order2PayDto;
import cn.madis.ymcc.service.ICourseOrderService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component//下面注解包含可不打
@RocketMQTransactionListener(txProducerGroup = "TxOrder2PayGroup")
@Slf4j
public class Order2PayTransMsgListener implements RocketMQLocalTransactionListener {

    @Autowired
    private ICourseOrderService courseOrderService;
    //执行本地事务
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
        //没有参数执行本地事务，直接回滚
        if (arg == null){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        CourseOrder courseOrder = (CourseOrder) arg;

        try { //执行本地订单保存
            courseOrderService.savaOrderItem(courseOrder);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    //检查本地事务
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        try {
            byte[] payload = (byte[])message.getPayload();
            String s = new String(payload, StandardCharsets.UTF_8);
            Order2PayDto order2PayDto = JSONObject.parseObject(s, Order2PayDto.class);
            CourseOrder courseOrder = courseOrderService.selectByOrderNo(order2PayDto.getOrderNo());
            if (courseOrder != null){
                return RocketMQLocalTransactionState.COMMIT;
            }
            return RocketMQLocalTransactionState.ROLLBACK;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.UNKNOWN;
        }

    }
}
